<template>
  <div id="app">
    <el-card shadow="always" align="center">
      {{studentSearch}}
      <!--1. 条件查询部分-->
      <el-form :inline="true" :model="studentSearch" class="demo-form-inline" align="left" style="margin-left: 40px;">
        <el-form-item>
          <el-input v-model="studentSearch.sname" placeholder="学生姓名" size="medium"></el-input>
        </el-form-item>
        <el-form-item >
          <el-input v-model="studentSearch.addr" placeholder="学生住址" size="medium"></el-input>
        </el-form-item>
        <el-form-item >
          <el-select v-model="studentSearch.cid" placeholder="所在班级" size="medium">
            <el-option label="所有班级" value="0"></el-option>
            <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="search" size="medium" plain>查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addUI" size="medium" plain>添加</el-button>
        </el-form-item>
      </el-form>
      <!--2. 列表部分-->
      <el-table
              :data="students"
              align="center"
              style="width: 95%">
        <el-table-column
                label="学号"
                prop="sid"
                align="center"
                width="180"/>

        <el-table-column
                label="姓名"
                align="center"
                prop="sname"
                />
          <!--<template slot-scope="scope">-->
          <!--  <el-popover trigger="hover" placement="top">-->
          <!--    <p>姓名: {{ scope.row.name }}</p>-->
          <!--    <p>住址: {{ scope.row.address }}</p>-->
          <!--    <div slot="reference" class="name-wrapper">-->
          <!--      <el-tag size="medium">{{ scope.row.name }}</el-tag>-->
          <!--    </div>-->
          <!--  </el-popover>-->
          <!--</template>-->
        <el-table-column
                label="性别"
                prop="sex"
                align="center"/>
        <el-table-column
                label="年龄"
                prop="age"
                align="center"/>
        <el-table-column
                label="住址"
                prop="addr"
                align="center"/>
        <el-table-column
                label="所在班级"
                prop="cname"
                align="center"
                />
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--3. 分页导航-->
      <el-pagination
              align="right"
              style="margin-top: 20px;margin-right: 20px;"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="page"
              :page-sizes="[3, 6, 9, 12]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
      </el-pagination>
    </el-card>
    <!--添加或修改的对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false" >
      {{student}}
      <el-form :model="student"  :rules="rules" ref="ruleForm">
        <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
          <el-input v-model="student.sname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生性别" :label-width="formLabelWidth" prop="sex">
          <!--<el-input v-model="student.sex" autocomplete="off"></el-input>-->
          <el-radio v-model="student.sex" label="男">男</el-radio>
          <el-radio v-model="student.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
          <el-input v-model.number="student.age" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
          <el-input v-model="student.addr" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
          <el-select v-model="student.cid" placeholder="请选择所在班级">
            <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      // 自定义验证规则
      let validAge = (rule,value,callback) => {
        if (!value) {
          return callback(new Error('年龄不能为空'));
        }else if (!Number.isInteger(value)) {
          callback(new Error('年龄必须是数字'));
        }else if(value < 1 || value > 200){
          callback(new Error('年龄必须在1-200之间'));
        }else{
          callback()
        }
      };
      return {
        students: [],
        page:1,       // 当前页
        pageSize:3,   // 每页大小
        total:100,    // 总记录数
        studentSearch:{}, // 封装查询条件的学生对象
        classes:[],       // 所有班级
        title:'添加学生',  // 对话框的标题
        dialogFormVisible:false,  //对话框的显示或隐藏
        student:{},               //要添加或修改的学生对象
        formLabelWidth:'100px',   // 对话框提示文本的宽度
        rules: {                  // 定义验证规则
            sname:[
              {required:true,message:'请输入学生姓名.',trigger:'blur'}
            ],
            sex:[
              {required: true,message:'请选择性别.',trigger: 'change'}
            ],
            age:[
              {validator: validAge,trigger:'blur'}
            ],
            addr:[
              {required:true,message:'请输入地址.',trigger:'blur'}
            ],
            cid:[
              {required:true,message:'请选择所在班级.',trigger:'blur'}
            ]
        },
      }
    },
    created() {
      // this.findStudents()
      // this.findPage()
      this.search()
      // 查询所有班级
      this.findClasses()
    },
    methods: {
      //0. 分页查询
      findPage(){
        this.axios.get(`/student/findPage.do?page=${this.page}&pageSize=${this.pageSize}`).then(({data})=>{
          this.students = data.data.rows
          this.total = data.data.total
        })
      },
      //1. 查询所有班綵
      findClasses(){
        this.axios.get(`/classes/list.do`).then(({data})=>{
          this.classes = data.data
        })
      },
      //2. 开始分页带条件查询
      search(){
        this.axios.post(`/student/search.do?page=${this.page}&pageSize=${this.pageSize}`,this.studentSearch).then(({data}) => {
          console.log("data:",data)
          this.students = data.data.rows
          this.total = data.data.total
        })
      },
      //3. 添加学生界面
      addUI(){
        //3.1 修改对话框标题
        this.title = "添加学生"
        //3.2 清空对话框
        this.student = {}
        //3.3 打开对话框
        this.dialogFormVisible = true

      },
      //4. 提交表单
      submitForm(){
        this.$refs['ruleForm'].validate(valid => {
          if(valid){
            let url = "/student/add.do"
            if(this.student.sid) { // 修改操作
               url = "/student/update.do"
            }
            //执行添加或修改操作
            this.axios.post(url,this.student).then(({data}) => {
              console.log("data:",data)
              let _this = this
              if(data.code === 200){
                this.$message({
                  message: data.msg,
                  type: 'success',
                  onClose(){  // 当此消息框关闭时，自动触发
                    // ① 关闭对话框
                    _this.dialogFormVisible = false
                    // ② 刷新页面
                    _this.search()
                  }
                });
              }
            })
          }else{
            console.log("验证不通过。")
          }
        })
      },
      //1. 查询所有学生
      findStudents(){
        this.axios.get("/student/list.do").then(({data}) => {
          this.students = data.data
        })
      },
      //2. pageSize大小改变时调用
      handleSizeChange(val) {
        this.pageSize = val
        // this.findPage()
        this.search()
        console.log(`每页 ${val} 条`);
      },
      //3. 当前页改变时调用
      handleCurrentChange(val) {
        this.page = val
        // this.findPage()
        this.search()
        console.log(`当前页: ${val}`);
      },
      // 修改操作
      handleEdit(index, row) {
        //1. 修改对话框标题
        this.title = "修改学生"
        //2. 打开对话框
        this.dialogFormVisible = true
        //3. 将当前行的记录数据row赋值给student
        this.student = row
        console.log(index, row);
      },
      handleDelete(index, row) {
        this.$confirm(`你确定要删除[${row.sname}]？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 到后台执行删除操作
          this.axios.get(`/student/delete.do?sid=${row.sid}`).then(({data}) => {
             if(data.code === 200){
               let _this = this
               this.$message({
                 message: data.msg,
                 type: 'success',
                 onClose(){
                   _this.search()     // 重新刷新页面
                 }
               });
             }
          })
          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
        console.log(index, row);
      }
    }
  }
</script>
<style>

</style>
